package online1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket listenSocket=null;
    public TcpEchoServer(int port) throws IOException {
        this.listenSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true){
            Socket clientSocket=listenSocket.accept();
            processConnection(clientSocket);
        }
    }
    public void processConnection(Socket clientSocket) throws IOException {
        String log=String.format("[%s:%d] 客户端上线！",clientSocket.getInetAddress().toString()
                ,clientSocket.getPort());
        System.out.println(log);
       try(InputStream inputStream=clientSocket.getInputStream();
           OutputStream outputStream=clientSocket.getOutputStream()){
           while(true){
               Scanner scanner=new Scanner(inputStream);
               if (!scanner.hasNext()){
                   log=String.format("[%s:%d] 客户端下线！",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                   System.out.println(log);
                   return;
               }
               String request=scanner.nextLine();
               String response=process(request);
               PrintWriter writer=new PrintWriter(outputStream);
               writer.println(response);
               writer.flush();
               log=String.format("[%s:%d] req: %s; resp: %s",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
               System.out.println(log);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }finally {
           clientSocket.close();
       }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
}
